﻿
// ClickerDlg.cpp: 实现文件
//

#include "stdafx.h"
#include "Clicker.h"
#include "ClickerDlg.h"
#include "afxdialogex.h"
#include "CaptureTool.h"
#include "DefInfo/GameInfo.h"
#include "DefInfo/def_spell.h"
#include "PressKeyUtil.h"
#include "DB\DbTool.h"
#include "ListPublic.h"
#include "DefInfo/Team_Raid_Info.h"
#include "Routine/Common/CombatRoutine.h"
#include "Config_General_Dlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// 用于应用程序“关于”菜单项的 CAboutDlg 对话框

class CAboutDlg : public CDialogEx {
public:
	CAboutDlg();

	// 对话框数据
#ifdef AFX_DESIGN_TIME
	enum { IDD = IDD_ABOUTBOX };
#endif

protected:
	virtual void DoDataExchange(CDataExchange * pDX);   // DDX/DDV 支持

// 实现
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX) {
}

void CAboutDlg::DoDataExchange(CDataExchange * pDX) {
	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()


// CClickerDlg 对话框
#define ONMYKEY 0x00001

static CClickerDlg * inst_ptr = NULL;

CClickerDlg::CClickerDlg(CWnd * pParent /*=nullptr*/)
	: CDialogEx(IDD_CLICKER_DIALOG, pParent) {
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
	inst_ptr = this;
}

CClickerDlg * CClickerDlg::getInst() {
	return inst_ptr;
}

void CClickerDlg::DoDataExchange(CDataExchange * pDX) {
	CDialogEx::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_STATIC_STATE, text_state_);
	DDX_Control(pDX, IDC_STATIC_TARGET, text_target_);
	DDX_Control(pDX, IDC_LIST_MSG, list_action_);
	DDX_Control(pDX, IDC_LIST3, list_action_history_);
	DDX_Control(pDX, IDC_CHECK_ENABLE_BATTLE, btn_helper_enbale);
	DDX_Control(pDX, IDC_STATIC_BATTLE, text_battle_);
	DDX_Control(pDX, IDC_STATIC_RUNE, text_rune_);
	DDX_Control(pDX, IDC_COMBO_SEL_WINDOW, combo_sel_win);
}

BEGIN_MESSAGE_MAP(CClickerDlg, CDialogEx)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BUTTON_TestAction, &CClickerDlg::OnBnClickedButtonTestaction)
	ON_WM_TIMER()
	ON_WM_HOTKEY()
	ON_BN_CLICKED(IDC_BUTTON_BUFF, &CClickerDlg::OnBnClickedButtonBuff)
	ON_CBN_SELCHANGE(IDC_COMBO_SEL_WINDOW, &CClickerDlg::OnSelchangeComboSelWindow)
	ON_BN_CLICKED(IDC_BUTTON_CONFIG, &CClickerDlg::OnBnClickedButtonConfig)
END_MESSAGE_MAP()
enum TimerEvent {
	TE_Timer_Scan,
	TE_Timer_ClearAction,
};


// CClickerDlg 消息处理程序

BOOL CClickerDlg::OnInitDialog() {
	CDialogEx::OnInitDialog();
	// 将“关于...”菜单项添加到系统菜单中。
	// IDM_ABOUTBOX 必须在系统命令范围内。
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);
	CMenu * pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != nullptr) {
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty()) {
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}
	// 设置此对话框的图标。  当应用程序主窗口不是对话框时，框架将自动
	//  执行此操作
	SetIcon(m_hIcon, TRUE);			// 设置大图标
	SetIcon(m_hIcon, FALSE);		// 设置小图标
	// TODO: 在此添加额外的初始化代码
	// 设置定时器,准备
	DbTool::inst().ConnectDB();
	CaptureTool::inst().EnumDisplayDevices();
	CaptureTool::inst().FetchHandle();
	SetTimer(TE_Timer_Scan, 100, NULL);
	InitListMsg();
	InitRegisteKey();
	// InitSpell
	GameInfo::inst().Init();
	return TRUE;  // 除非将焦点设置到控件，否则返回 TRUE
}

void CClickerDlg::OnSysCommand(UINT nID, LPARAM lParam) {
	if ((nID & 0xFFF0) == IDM_ABOUTBOX) {
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else {
		CDialogEx::OnSysCommand(nID, lParam);
	}
}

// 如果向对话框添加最小化按钮，则需要下面的代码
//  来绘制该图标。  对于使用文档/视图模型的 MFC 应用程序，
//  这将由框架自动完成。

void CClickerDlg::OnPaint() {
	if (IsIconic()) {
		CPaintDC dc(this); // 用于绘制的设备上下文
		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
		// 使图标在工作区矩形中居中
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;
		// 绘制图标
		dc.DrawIcon(x, y, m_hIcon);
	}
	else {
		CDialogEx::OnPaint();
	}
}

//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CClickerDlg::OnQueryDragIcon() {
	return static_cast<HCURSOR>(m_hIcon);
}

void CClickerDlg::OnBnClickedButtonTestaction() {
	// TODO: 在此添加控件通知处理程序代码
	HWND hWnd = CaptureTool::inst().GetWowHWnd();
	if (hWnd) {
		for (int i = 0; i < 3; i++) {
			std::vector<unsigned char> key = { VK_OEM_MINUS };

			PressKeyUtil::inst().SendKey(key, 11);
			// 			::PostMessage(hWnd, WM_KEYDOWN, VK_OEM_MINUS, 1);
			// 			Sleep(50);
			// 			::PostMessage(hWnd, WM_KEYUP, VK_OEM_MINUS, 1);
			Sleep(1000);
			PressKeyUtil::inst().EndLock();
		}
	}
}


void CClickerDlg::OnTimer(UINT_PTR nIDEvent) {
	// TODO: 在此添加消息处理程序代码和/或调用默认值
	CDialogEx::OnTimer(nIDEvent);
	if (nIDEvent == TE_Timer_Scan) {
		// 获取窗口截图.
		// 如果有句柄, 则截屏获取像素
		if (!CaptureTool::inst().IsWindowEnable()) {
			CaptureTool::inst().ResetData();
			CaptureTool::inst().FetchHandle();
		}
		GameInfo::inst().SetShowInfo(false);
		if (CaptureTool::inst().IsWindowEnable()) {
			//			SaveHwndToBmpFile(CaptureTool::inst().GetWowHWnd(), _T(".//12.bmp"));
			auto tick = GetTickCount64();
			if (CaptureTool::inst().CaptureScrenn()) {
				ShowInfo();
			}
			auto cur_tick = GetTickCount64();
			CString str_tick;
			str_tick.Format(L"use time: %d ms\n", cur_tick - tick);
			OutputDebugString(str_tick);
		}
		ShowSelCombo();
	}
	if (nIDEvent == TE_Timer_ClearAction) {
		list_action_history_.DeleteAllItems();
		DelTimerClearAction();
	}
}

bool CClickerDlg::ShowInfo() {
	if (!GameInfo::inst().ObtainInfo()) {
		return false;
	}
	ShowBaseInfo();
	ShowRuneInfo();
	ShowActionInfo();
	IRoutine* routine = CombatRoutine::inst().GetRoutine(GameInfo::inst().GetPlayerClass(), (SpecializationID)GameInfo::inst().GetPlayerSpecializationID());
	if (routine)
	{
		routine->ChooseBattleAction();
	}
	ClearActionHistory();
	return true;
}

void CClickerDlg::ClearActionHistory() {
	if (GameInfo::inst().PlayerInBattle() == 0) {
		if (time_want_clear_action_ == 0) {
			SetTimer(TE_Timer_ClearAction, 10000, NULL);
			time_want_clear_action_ = time(NULL);
		}
	}
	else {
		DelTimerClearAction();
	}
}


void CClickerDlg::ShowBaseInfo() {
	//////////////////////////////////////////////////////////////////////////
	CString text;
	text.Format(L"玩家[职业:%s-%d] HP: %d/%d,MP: %d/%d.可用符文:%d.",
		GameInfo::inst().GetPlayerClassName(), GameInfo::inst().GetPlayerSpec(),
		GameInfo::inst().GetPlayer().player_hp, GameInfo::inst().GetPlayer().player_hp_max,
		GameInfo::inst().GetPlayerMana(), GameInfo::inst().GetPlayerManaMax(),
		GameInfo::inst().GetRuneReadyCount());
	text_state_.SetWindowText(text);
	text.Format(L"目标 HP: %d/%d", GameInfo::inst().GetTargetHp(), GameInfo::inst().GetTargetHpMax());
	if (GameInfo::inst().PlayerInBattle() == 1) {
		text.Append(L" 在战斗中");
	}
	else {
		text.Append(L" 不在战斗");
	}
	if (GameInfo::inst().TargetIsEnemy()) {
		text.Append(L" 是敌人");
	}
	else {
		text.Append(L" 不是敌人");
	}
	if (GameInfo::inst().GetTargetSpellCanInterupt()) {
		text.Append(L"  可打断");
	}
	else {
		text.Append(L"  不可打断");
	}
	text_target_.SetWindowText(text);
	text.Format(L"平均掉血%.2f, 统计时间%.2f", GameInfo::inst().GetLostHP_InFiveSecond(), GameInfo::inst().GetElapseTime());
	text_battle_.SetWindowText(text);
}


void CClickerDlg::DelTimerClearAction() {
	KillTimer(TE_Timer_ClearAction);
	time_want_clear_action_ = 0;
}


void CClickerDlg::InitRegisteKey() {
	RegisterHotKey(GetSafeHwnd(), ONMYKEY, NULL, VK_NUMPAD4);
	RegisterHotKey(GetSafeHwnd(), ONMYKEY, NULL, VK_NUMPAD7);
	RegisterHotKey(GetSafeHwnd(), ONMYKEY, NULL, VK_XBUTTON1);
	RegisterHotKey(GetSafeHwnd(), ONMYKEY, NULL, VK_XBUTTON2);
	btn_helper_enbale.SetCheck(1);
}

void CClickerDlg::ShowRuneInfo() {
	CString global_cd;
	global_cd.Format(L"gcd:%d ", GameInfo::inst().GetGlobalCD());
	CString text_rune = global_cd + L" rune:";
	for (int i = 1; i <= 6; i++) {
		auto & rune = GameInfo::inst().GetRune(i);
		if (rune.rune_rest_time == 0) {
			text_rune.AppendFormat(L",%d[%d]", rune.rune_rest_time, rune.rune_slot_amount);
		}
		else {
			text_rune.AppendFormat(L",%d", rune.rune_rest_time);
		}
	}
	text_rune_.SetWindowText(text_rune);
}

void CClickerDlg::InitListMsg() {
	list_action_.InsertColumn(0, L"索引", LVCFMT_LEFT, 40);//插入列
	list_action_.InsertColumn(1, L"技能名称", LVCFMT_LEFT, 80);
	list_action_.InsertColumn(2, L"技能ID", LVCFMT_LEFT, 60);
	list_action_.InsertColumn(3, L"CD", LVCFMT_LEFT, 30);
	list_action_.InsertColumn(4, L"GCD", LVCFMT_LEFT, 40);
	list_action_.InsertColumn(5, L"范围内", LVCFMT_LEFT, 50);
	list_action_.InsertColumn(6, L"类型", LVCFMT_LEFT, 40);
	for (int i = 0; i < 48; i++) {
		CString str;
		str.Format(L"%d", i);
		int nRow = list_action_.InsertItem(i, str);//插入行
	}
	//////////////////////////////////////////////////////////////////////////
	list_action_history_.InsertColumn(0, L"ID", LVCFMT_LEFT, 40);//插入列
	list_action_history_.InsertColumn(1, L"队列", LVCFMT_LEFT, 120);
	list_action_history_.InsertColumn(2, L"时间", LVCFMT_LEFT, 70);
}

void CClickerDlg::SetActionState(int index, CString text) {
	list_action_.SetItemText(index, 1, text);
}



void CClickerDlg::SetActionCDMsg(int index, LPCWSTR msg, int spell_id, int cd, int gcd) {
	JudgeSetListItem(list_action_, index, 1, CString(msg));
	CString str_cd;
	str_cd.Format(L"%d", spell_id);
	JudgeSetListItem(list_action_, index, 2, str_cd);
	str_cd.Format(L"%d", cd);
	JudgeSetListItem(list_action_, index, 3, str_cd);
	str_cd.Format(L"%.1f", gcd*1.0f / 10);
	JudgeSetListItem(list_action_, index, 4, str_cd);
}

void CClickerDlg::SetActionCDMsg_Blank(int index) {
	JudgeSetListItem(list_action_, index, 1, CString(L""));
	CString str_cd;
	JudgeSetListItem(list_action_, index, 2, str_cd);
	JudgeSetListItem(list_action_, index, 3, str_cd);
	JudgeSetListItem(list_action_, index, 4, str_cd);
}

void CClickerDlg::SetActionRangeTypeMsg(int index, int in_range, int type) {
	CString str_cd;
	str_cd.Format(L"%d", in_range);
	JudgeSetListItem(list_action_, index, 5, str_cd);
	str_cd.Format(L"%d", type);
	JudgeSetListItem(list_action_, index, 6, str_cd);
}

void CClickerDlg::SetActionRangeTypeMsg_Blank(int index) {
	CString str_cd;
	JudgeSetListItem(list_action_, index, 5, str_cd);
	JudgeSetListItem(list_action_, index, 6, str_cd);
}

void CClickerDlg::ShowSelCombo()
{
	auto & window_set = CaptureTool::inst().GetWindowSet();
	if (window_set.vec_hwnd.size() > 0)
	{
		if (combo_sel_win.GetCount() < window_set.vec_hwnd.size())
		{
			size_t size = window_set.vec_hwnd.size() - combo_sel_win.GetCount();
			for (size_t i = 0; i < size; i++)
			{
				combo_sel_win.AddString(L"");
			}
		}
		int pid = CaptureTool::inst().GetSelWindowPid();
		int sel = 0;
		for (size_t i = 0; i < window_set.vec_hwnd.size(); i++)
		{
			auto& item = window_set.vec_hwnd[i];
			CString win_text;
			CA2T name(item.name.c_str());
			win_text.Format(L"ID:%d %s", item.pid, name.m_psz);
			CString cur_text;
			combo_sel_win.GetLBText((int)i, cur_text);
			if (cur_text != win_text)
			{
				combo_sel_win.DeleteString((int)i);
				combo_sel_win.InsertString((int)i, win_text);
			}
			if (pid == item.pid)
			{
				sel = (int)i;
			}
		}
		int cur_sel = combo_sel_win.GetCurSel();
		if (cur_sel == -1)
		{
			combo_sel_win.SetCurSel(sel);
		}
	}
}

void CClickerDlg::ShowActionInfo() {
	for (int iAction = 0; iAction < GameInfo::inst().GetActionCount(); iAction++) {
		auto & action = GameInfo::inst().GetActionByIndex(iAction);
		if (action.type == 1)
		{
			auto & config = GameInfo::inst().GetSpellConfigBySpellID(action.spell_id);
			int gcd = config.need_gcd > 0 ? GameInfo::inst().GetGlobalCD() : 0;
			SetActionCDMsg(iAction + 1, config.name_cn, config.spell_id, action.cool_down, gcd);
			SetActionRangeTypeMsg(iAction + 1, action.in_range, action.type);
		}
		else if (action.type == 0) {
			SpellConfig config;
			SetActionCDMsg_Blank(iAction + 1);
			SetActionRangeTypeMsg_Blank(iAction + 1);
		}
	}
}

void CClickerDlg::OnHotKey(UINT nHotKeyId, UINT nKey1, UINT nKey2) {
	// TODO: 在此添加消息处理程序代码和/或调用默认值
	// OutputDebugString(L"你按下了 num4 键");
	if (nHotKeyId)
	{
		if (nKey2 == VK_NUMPAD4 || nKey2 == VK_XBUTTON1)
		{
			PressKeyUtil::inst().press_battle_enbale = !PressKeyUtil::inst().press_battle_enbale;
			btn_helper_enbale.SetCheck((int)PressKeyUtil::inst().press_battle_enbale);
		}
		else if (nKey2 == VK_NUMPAD7 || nKey2 == VK_XBUTTON2)
		{
			GameInfo::inst().GetRoutineConfig().general_config.force_attack_target = !GameInfo::inst().GetRoutineConfig().general_config.force_attack_target;
			if (Config_General_Dlg::Inst())
			{
				Config_General_Dlg::Inst()->SetCheck(2, GameInfo::inst().GetRoutineConfig().general_config.force_attack_target);
			}
		}
	}
	CDialogEx::OnHotKey(nHotKeyId, nKey1, nKey2);
}


void CClickerDlg::OnBnClickedButtonBuff() {
	// TODO: 在此添加控件通知处理程序代码
	if (buff_dlg_ == NULL) {
		buff_dlg_ = new BuffDlg();
		buff_dlg_->Create(IDD_DIALOG_BUFF, this);
	}
	if (!buff_dlg_->IsWindowVisible()) {
		// 显示非模态对话框
		buff_dlg_->ShowWindow(SW_SHOW);
	}
	else {
		buff_dlg_->ShowWindow(SW_HIDE);
	}
}


void CClickerDlg::OnSelchangeComboSelWindow()
{
	int sel = combo_sel_win.GetCurSel();
	CaptureTool::inst().SetSelWindowIndex(sel);
	CaptureTool::inst().FetchHandle();
}


void CClickerDlg::OnBnClickedButtonConfig()
{
	// TODO: 在此添加控件通知处理程序代码
	if (config_dlg_ == NULL) {
		config_dlg_ = new ConfigDlg();
		config_dlg_->Create(IDD_DIALOG_SPELL_CONFIG, this);
	}
	if (!config_dlg_->IsWindowVisible()) {
		// 显示非模态对话框
		config_dlg_->ShowWindow(SW_SHOW);
	}
	else {
		config_dlg_->ShowWindow(SW_HIDE);
	}
}

